<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose :title="title" :width="'70%'" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="UfMallFreightTemplateForm" />
    <div v-if="isUpdate" style="margin: 10px 0">
      <a-button type="primary" ghost @click="handleOpenFeeRuleModal">新增收费规则</a-button>
    </div>
    <a-table v-if="isUpdate" :loading="loading" :columns="feeColumns" :data-source="feeRulesDataSource" :pagination="false" size="small">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'deliveryAreas'">
          {{ getTextByCodes2(record.deliveryAreas).join(' | ') }}
        </template>
        <template v-if="column.key === 'operate'">
          <div>
            <a-button type="link" size="small" @click="handleOpenEditFeeRuleModal(record)">编辑</a-button>
            <a-button type="link" danger size="small" @click="handleRemoveFeeRule(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <div v-if="isUpdate" style="margin: 10px 0">
      <a-button type="primary" @click="handleOpenFeeIncludedRuleModal" ghost>新增包邮规则</a-button>
    </div>
    <a-table
      v-if="isUpdate"
      :loading="loading"
      :columns="includedRuleColumns"
      :data-source="includedRulesDataSource"
      :pagination="false"
      size="small"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'deliveryAreas'">
          {{ getTextByCodes2(record.deliveryAreas).join(' | ') }}
        </template>
        <template v-if="column.key === 'includedType'">
          <div v-if="record['includedType'] == 'ONLY_REACH_AMOUNT'"> 满 {{ record['reachAmount'] }} 元包邮 </div>
          <div v-if="record['includedType'] == 'ONLY_REACH_DATA'"> 小于 {{ record['reachData'] }}{{ getSuffix2() }} 包邮 </div>
          <div v-if="record['includedType'] == 'REACH_DATA_AND_AMOUNT'">
            满 {{ record['reachAmount'] }} 元，且小于 {{ record['reachData'] }}{{ getSuffix2() }} 包邮
          </div>
        </template>
        <template v-if="column.key === 'operate'">
          <div>
            <a-button type="link" size="small" @click="handleOpenEditFeeIncludedRuleModal(record)">编辑</a-button>
            <a-button type="link" danger size="small" @click="handleRemoveFeeIncludedRule(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <uf-mall-freight-fee-rule-modal @register="registerFeeRuleModal" @success="reloadTableData" />
    <uf-mall-freight-fee-included-rule-modal @register="registerFeeIncludedRuleModal" @success="reloadTableData" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { formSchema } from '../UfMallFreightTemplate.data';
  import { get, removeFeeIncludedRule, removeFeeRule, saveOrUpdate } from '../UfMallFreightTemplate.api';
  import { useModal } from '@/components/Modal';
  import UfMallFreightFeeRuleModal from '@/views/goods/freight_fee/components/UfMallFreightFeeRuleModal.vue';
  import { getTextByCodes2 } from '../../../../components/Form/src/utils/Area';
  import UfMallFreightFeeIncludedRuleModal from '@/views/goods/freight_fee/components/UfMallFreightFeeIncludedRuleModal.vue';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const feeRulesDataSource = ref([]);
  const includedRulesDataSource = ref([]);
  const calculateType = ref('');
  const templateId = ref('');
  const loading = ref(false);
  //注册model
  const [registerFeeRuleModal, { openModal: openFeeRuleModal }] = useModal();
  const [registerFeeIncludedRuleModal, { openModal: openFeeIncludedRuleModal }] = useModal();
  let tempFormSchema: FormSchema[] = Object.assign([], formSchema);
  for (let i = 0; i < tempFormSchema.length; i++) {
    let item = tempFormSchema[i];
    if (item.field == 'calculateType') {
      item.componentProps['onChange'] = function (val) {
        calculateType.value = val;
      };
    }
  }
  let includedRuleColumns = computed(() => {
    return [
      {
        title: '地区',
        dataIndex: 'deliveryAreas',
        key: 'deliveryAreas',
        width: '450px',
      },
      {
        title: '包邮条件',
        dataIndex: 'includedType',
        key: 'includedType',
        width: '200px',
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        align: 'right',
        width: '130px',
      },
    ];
  });

  function getSuffix() {
    if (calculateType.value == 'QUANTITY') {
      return '件（个）';
    } else if (calculateType.value == 'WEIGHT') {
      return '重（kg）';
    } else if (calculateType.value == 'VOLUME') {
      return '体积（m³）';
    }
  }

  function getSuffix2() {
    if (calculateType.value == 'QUANTITY') {
      return '件';
    } else if (calculateType.value == 'WEIGHT') {
      return 'kg';
    } else if (calculateType.value == 'VOLUME') {
      return 'm³';
    }
  }

  let feeColumns = computed(() => {
    let startingDataTitle = '首';
    let continuedDataTitle = '续';
    startingDataTitle += getSuffix();
    continuedDataTitle += getSuffix();
    return [
      {
        title: '地区',
        dataIndex: 'deliveryAreas',
        key: 'deliveryAreas',
        width: '450px',
      },
      {
        title: startingDataTitle,
        dataIndex: 'startingData',
        key: 'startingData',
        align: 'right',
        width: '80px',
      },
      {
        title: '费用（元）',
        dataIndex: 'startingAmount',
        key: 'startingAmount',
        align: 'right',
        width: '80px',
      },
      {
        title: continuedDataTitle,
        dataIndex: 'continuedData',
        key: 'continuedData',
        align: 'right',
        width: '80px',
      },
      {
        title: '续费（元）',
        dataIndex: 'continuedAmount',
        key: 'continuedAmount',
        align: 'right',
        width: '80px',
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        align: 'right',
        width: '130px',
      },
    ];
  });
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField, getFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: tempFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  async function reloadTableData() {
    loading.value = true;
    try {
      let recordData = await get(templateId.value);
      feeRulesDataSource.value = recordData.feeRules;
      includedRulesDataSource.value = recordData.includedRules;
      calculateType.value = recordData.calculateType;
    } catch (e) {
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 800);
    }
  }

  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    //重置表单
    await resetFields();
    setDrawerProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, showFooter: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.showFooter;
    if (unref(isUpdate)) {
      templateId.value = data.record.id;
      let recordData = await get(data.record.id);
      reloadTableData();
      //表单赋值
      await setFieldsValue({
        ...recordData,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  const type = computed(() => {
    let fields = getFieldsValue();
    return fields;
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function handleOpenFeeRuleModal() {
    openFeeRuleModal(true, {
      isUpdate: false,
      showFooter: true,
      calculateType: calculateType.value,
      templateId: templateId.value,
    });
  }
  function handleOpenEditFeeRuleModal(record) {
    openFeeRuleModal(true, {
      isUpdate: true,
      showFooter: true,
      calculateType: calculateType.value,
      record: unref(record),
      templateId: templateId.value,
    });
  }

  function handleRemoveFeeRule(record) {
    removeFeeRule(record.id).then(() => {
      reloadTableData();
    });
  }

  function handleOpenFeeIncludedRuleModal() {
    openFeeIncludedRuleModal(true, {
      isUpdate: false,
      showFooter: true,
      calculateType: calculateType.value,
      templateId: templateId.value,
    });
  }

  function handleRemoveFeeIncludedRule(record) {
    removeFeeIncludedRule(record.id).then(() => {
      reloadTableData();
    });
  }

  function handleOpenEditFeeIncludedRuleModal(record) {
    openFeeIncludedRuleModal(true, {
      isUpdate: true,
      showFooter: true,
      calculateType: calculateType.value,
      record: unref(record),
      templateId: templateId.value,
    });
  }
</script>

<style lang="less">
  #zwx-area-link .ant-select {
    width: 100% !important;
  }

  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
